package cn.ncu.wechat.service.impl;

import cn.ncu.wechat.model.dto.ProductBatchRequest;
import cn.ncu.wechat.util.Result;
import cn.ncu.wechat.vo.ProductVO;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ncu.wechat.model.Product;
import cn.ncu.wechat.service.ProductService;
import cn.ncu.wechat.dao.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

/**
* @author 
* @description 针对表【product(商品表)】的数据库操作Service实现
* @createDate 2025-01-07 16:17:22
*/
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product>
    implements ProductService{

    @Autowired
    private ProductMapper productMapper;

    public Result<?> getProductList(int page,int pageSize){
        try {
            Page<Product> pageInfo = new Page<>(page, pageSize);
            Page<Product> productPage = productMapper.selectPage(pageInfo, new QueryWrapper<Product>().select("id","image","name","points","sold_count","stock"));
            List<Product> list = productPage.getRecords();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("list",list);
            jsonObject.put("total",list.size());
            return Result.success(jsonObject);
        }catch (Exception e){
            return Result.error(500,"服务器异常:"+e);
        }

    }

    public Result<?> getProductDetail(Long id){
        try {
            QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
            productQueryWrapper.eq("id",id);
            Product productInfo = productMapper.selectOne(productQueryWrapper);
            if (productInfo==null){
                return Result.fail(404,"资源不存在");
            }
            ProductVO productVO = new ProductVO();
            productVO.toProductVo(productInfo);
            return Result.success(productVO);
        }catch (Exception e){
            return Result.error(500,"服务器异常:"+e);
        }
    }

    @Override
    public Result<?> getPurchaseTypes() {
        try{
            // 创建一个List来存储字典
            List<Map<String, String>> type_list = new ArrayList<>();

            // 创建第一个字典
            Map<String, String> dict1 = new HashMap<>();
            dict1.put("value", "price");
            dict1.put("label", "价格商品");
            dict1.put("description", "价格商品");
            type_list.add(dict1);

            // 创建第二个字典
            Map<String, String> dict2 = new HashMap<>();
            dict2.put("value", "points");
            dict2.put("label", "积分商品");
            dict2.put("description", "积分商品");
            type_list.add(dict2);

            // 创建第三个字典
            Map<String, String> dict3 = new HashMap<>();
            dict3.put("value", "gift");
            dict3.put("label", "兑礼商品");
            dict3.put("description", "兑礼商品");
            type_list.add(dict3);
            return Result.success(type_list);
        } catch (Exception e) {
            return Result.error(500,"获取失败");
        }
    }

    @Override
    public Result uploadProductImage(MultipartFile file) {
        return null;
    }

    @Override
    public Result productBatch(ProductBatchRequest request) {
        // 获取请求参数
        List<Long> ids = request.getIds();
        String action = request.getAction();
        String value = request.getValue();

        // 根据 action 执行不同的逻辑
        switch (action) {
            case "status":
                // 更新状态逻辑
                return updateStatus(ids, value);
            case "delete":
                // 删除逻辑
                return deleteProducts(ids);
            default:
                return Result.error(400,"参数错误");
        }
    }
    private Result updateStatus(List<Long> ids, String status) {
        try {
            // 参数校验
            if (ids == null || ids.isEmpty()) {
                return Result.error(400, "商品ID列表不能为空");
            }
            if (status == null || (!status.equals("1") && !status.equals("2"))) {
                return Result.error(400, "状态值只能是1或2");
            }

            List<Product> existingProducts = list(new LambdaQueryWrapper<Product>()
                    .in(Product::getId, ids));

            if (existingProducts.isEmpty()) {
                return Result.error(400, "未找到任何指定的商品");
            }

            // 找出不存在的商品ID
            List<Long> existingIds = existingProducts.stream()
                    .map(Product::getId)
                    .collect(Collectors.toList());
            List<Long> nonExistingIds = ids.stream()
                    .filter(id -> !existingIds.contains(id))
                    .collect(Collectors.toList());

            if (!nonExistingIds.isEmpty()) {
                return Result.error(400, "部分商品不存在");
            }

            // 构建更新条件
            UpdateWrapper<Product> updateWrapper = new UpdateWrapper<>();
            updateWrapper.in("id", ids)
                        .set("status", status)
                        .set("update_time", new Date());

            // 执行批量更新
            boolean success = update(updateWrapper);
            
            if (success) {
                return Result.success("更新成功");
            } else {
                return Result.error(500, "更新失败");
            }

        } catch (Exception e) {
            log.error("批量更新商品状态异常：", e);
            throw new RuntimeException("更新商品状态失败：" + e.getMessage());
        }
    }
    private Result deleteProducts(List<Long> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                    return Result.error(400, "商品ID列表不能为空");
                }

            boolean success = this.removeByIds(ids);

            if (success) {
                return Result.success();
            } else {
                return Result.error(500, "删除失败");
            }
        } catch (Exception e) {
            return Result.error(500, "删除失败" + e.getMessage());
        }
        
    }
}




